<?php
class My_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract
{
	protected $_auth;
	protected $_acl;

	public function preDispatch(Zend_Controller_Request_Abstract $request)
	{
		$auth = Zend_Auth::getInstance();
		//$acl = new My_Acl($auth);

		$acl = Zend_Registry::get('acl');

		$this->_auth= $auth;
		$this->_acl=$acl;
		$module = $this->getRequest()->getModuleName();
		$controler = $request->getControllerName();
		$action = $request->getActionName();
		$resourceId = $module .':' .$controler;
		$indentify = $auth->getIdentity();
		if (isset($indentify)) {
			$indentify = $auth->getIdentity();
			$iInfo = Front_Model_UserMapper::objectToArray($indentify);
			$roleStr = $iInfo['roleStr'];

			if (!$acl->isAllowed($roleStr, $resourceId,$action)) {
				$this->redirect($roleStr);
			}
		} else { //Front
			$roleStr = 'front';
			if (!$acl->isAllowed($roleStr, $resourceId,$action)) {
				$module = $roleStr;
				$controller = 'authentication';
				$action = 'login';
				$baseUrl = new Zend_View_Helper_BaseUrl();
				$url = $baseUrl->getBaseUrl();
				$url = $url .'/' .$module .'/' .$controller .'/' .$action;
				$this->getResponse()->setRedirect($url);
			}
		}
	}

	public static function getRole() {
		$auth = Zend_Auth::getInstance();
		$indentify = $auth->getIdentity();
		if (isset($indentify)) {
			$iInfo = Front_Model_UserMapper::objectToArray($indentify);
			$roleStr = $iInfo['roleStr'];
			return $roleStr;
		} else {
			return;
		}
	}

	public static function goHomePage(Zend_Controller_Response_Abstract $response) {
		$baseUrl = new Zend_View_Helper_BaseUrl();
		$url = $baseUrl->getBaseUrl();
		$response->setRedirect($url);
	}

	public static function goPage(Zend_Controller_Response_Abstract $response, $module, $controller, $action) {
		$baseUrl = new Zend_View_Helper_BaseUrl();
		$url = $baseUrl->getBaseUrl();
		$url = $url.'/'.$module.'/'.$controller.'/'.$action;
		$response->setRedirect($url);
	}

	public function redirect($roleStr) {
		$module = $roleStr;
		$controller = 'index';
		$action = 'index';
		$baseUrl = new Zend_View_Helper_BaseUrl();
		$url = $baseUrl->getBaseUrl();
		$url = $url .'/' .$module;// .'/' .$controller .'/' .$action;
		$this->getResponse()->setRedirect($url);
		//		if ($roleStr == '') {
		//
		//		} else if ($roleStr == ''){
		//
		//		} else if ($roleStr == ''){
		//
		//		}
	}

	public function postDispatch(Zend_Controller_Request_Abstract $request) {

		$frontController = Zend_Controller_Front::getInstance();
		if ($this->getResponse()->isException()) {
			$frontController = Zend_Controller_Front::getInstance();
		}
	}
}
?>